#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdlib.h>

typedef struct {
	int integer;
	char string[24];
} RECORD;

#define NRRECORDS (100)

int main()
{
	RECORD record, *mapped;
	int i, f;
	FILE *fp;

	fp = fopen("records.txt","w+"); /* w+ file can read and write, if not exist creat it*/
	for(i = 0; i < NRRECORDS; i++) {
		record.integer = i;
		sprintf(record.string, "RECORD-%d\n", i);
		/*fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) write nmemb x size*/
		fwrite(&record, sizeof(record), 1, fp);
	}
	fclose(fp);
	
	fp = fopen("records.txt", "r+");
	fseek(fp, 43*sizeof(record), SEEK_SET);
	fread(&record, sizeof(record), 1, fp);

	record.integer = 143;
	sprintf(record.string, "RECORD-%d\n", record.integer);
	
	fseek(fp, 43*sizeof(record), SEEK_SET);
	fwrite(&record, sizeof(record), 1, fp);
	
	fclose(fp);

	/* used low-level i/o to open file */
	f = open("records.txt", O_RDWR);
	mapped = (RECORD *)mmap(0, NRRECORDS*sizeof(record), PROT_READ|PROT_WRITE, MAP_SHARED, f, 0);
	mapped[43].integer = 243;
	sprintf(mapped[43].string, "RECORD-%d", mapped[43].integer);
	
	msync((void *)mapped, NRRECORDS*sizeof(record), MS_ASYNC);
	munmap((void *)mapped, NRRECORDS*sizeof(record));

	close(f);

	return 0;
}
